package usagms

import (
    "errors"
	"strconv"
	"encoding/json"
	"thirdpaysdk/utils/signature"
	"thirdpaysdk/utils/mapstruct"
)

type UsagmsNotifyMsg struct {
	Time           string  `json:"time"`
	NonceStr       string  `json:"nonce_str"`
	Sign           string  `json:"sign"`
	PartnerOrderId string  `json:"partner_order_id"`
	OrderId        string  `json:"order_id"`
	TotalFee       int     `json:"total_fee"`
	RealFee        int     `json:"real_fee"`
	Rate           float64 `json:"rate"`
	Currency       string  `json:"currency"`
	Channel        string  `json:"channel"`
	CreateTime     string  `json:"create_time"`
	PayTime        string  `json:"pay_time"`
}

func UsagmsNotify(body []byte, mchId, appKey string) (map[string]interface{}, error){
	var response UsagmsNotifyMsg
	err := json.Unmarshal(body, &response)
	if err != nil {
		return map[string]interface{}{}, err
	}
	partnerCode := mchId
	credentialCode := appKey
	signTime, err := strconv.ParseInt(response.Time, 10, 64)
	if err != nil {
	   return map[string]interface{}{}, err
	}
	sign := signature.MakeSha256Sign(partnerCode, signTime, response.NonceStr, credentialCode)
	if response.Sign != sign {
	    returnMsg := "sign is invalid"
		return map[string]interface{}{}, errors.New(returnMsg)
	}
	if response.TotalFee != response.RealFee {
	    returnMsg := "total_fee is not equal real_fee"
		return map[string]interface{}{}, errors.New(returnMsg)
	}
	rspMap :=  mapstruct.Struct2Map(response, "json")
	return rspMap, nil
}
